package com.audaque.springboot.foshanupload.web.mpdemo.mpgt.dao.impl;


import cn.hutool.core.bean.BeanUtil;
import com.audaque.springboot.foshanupload.core.model.qo.BaseQo;
import com.audaque.springboot.foshanupload.core.model.qo.IdQo;
import com.audaque.springboot.foshanupload.core.model.qo.page.Page;
import com.audaque.springboot.foshanupload.pagehelper.component.MybatisPageHelperPageConvert;
import com.audaque.springboot.foshanupload.web.mpdemo.mpgt.dao.SysUserMpgtDao;
import com.audaque.springboot.foshanupload.web.mpdemo.mpgt.mapper.SysUserMpgtMapper;
import com.audaque.springboot.foshanupload.web.mpdemo.mpgt.model.kbo.SysUserMpgtKbo;
import com.audaque.springboot.foshanupload.web.mpdemo.mpgt.model.pojo.SysUserMpgtPojo;
import com.audaque.springboot.foshanupload.web.mpdemo.mpgt.model.qo.SysUserMpgtQo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author zgb
 * @since 2023-03-01
 */

@Slf4j
@Repository
public class SysUserMpgtDaoImpl implements SysUserMpgtDao {

    @Autowired
    private SysUserMpgtMapper sysUserMpgtMapper;

    @Resource
    private MybatisPageHelperPageConvert mybatisPageHelperPageConvert;

    @Override
    public String insert(SysUserMpgtPojo pojo, Boolean ignoreDuplicateExceptionYn) throws Exception {
        try {
            sysUserMpgtMapper.insert(pojo);
        } catch (Exception exception) {
            String s;
            Throwable cause = exception.getCause();
            if (cause instanceof SQLIntegrityConstraintViolationException) {
                String sqlState = ((SQLIntegrityConstraintViolationException) cause).getSQLState();
                s = "Dao.insert:表中已存在主键,已设置允许忽略次此异常";
                log.debug(s);
                if (!ignoreDuplicateExceptionYn) {
                    throw new Exception(s);
                }
            } else {
                s = "Dao.insert:保存失败";
                log.error(s, exception);
                throw new Exception(s);
            }

        }

        Long id = pojo.getUserId();
        if (id == null) {
            return null;
        }
        return Long.toString(id);
    }
    @Override
    public String insertBatch(List<SysUserMpgtPojo> pojoList , Boolean ignoreDuplicateExceptionYn) throws Exception {
        try {
            sysUserMpgtMapper.insertBatchSomeColumn(pojoList);
        } catch (Exception exception) {
            String s;
            Throwable cause = exception.getCause();
            if (cause instanceof SQLIntegrityConstraintViolationException) {
                String sqlState = ((SQLIntegrityConstraintViolationException) cause).getSQLState();
                s = "Dao.insert:表中已存在主键,已设置允许忽略次此异常";
                log.debug(s);
                if (!ignoreDuplicateExceptionYn) {
                    throw new Exception(s);
                }
            } else {
                s = "Dao.insert:保存失败";
                log.error(s, exception);
                throw new Exception(s);
            }

        }
        List<String> collect = pojoList.stream().map(e ->Long.toString( e.getUserId())).collect(Collectors.toList());
        return String.join(",",collect);

    }


    @Override
    public String insertBatch(Collection<SysUserMpgtPojo> pojoList, int batchSize , Boolean ignoreDuplicateExceptionYn) throws Exception {
        List<String> collect =new ArrayList<>(pojoList.size());
        try {

            int size = pojoList.size();
            int idxLimit = Math.min(batchSize, size);
            int i = 1;
            //保存单批提交的数据集合
            List<SysUserMpgtPojo> oneBatchList = new ArrayList<>();
            for (Iterator<SysUserMpgtPojo> var7 = pojoList.iterator(); var7.hasNext(); ++i) {
                SysUserMpgtPojo element = var7.next();
                oneBatchList.add(element);
                if (i == idxLimit) {
                    sysUserMpgtMapper.insertBatchSomeColumn(oneBatchList);
                    List<String> collect1 = oneBatchList.stream().map(e -> Long.toString(e.getUserId())).collect(Collectors.toList());
                    collect.addAll(collect1);
                    //每次提交后需要清空集合数据
                    oneBatchList.clear();
                    idxLimit = Math.min(idxLimit + batchSize, size);
                }
            }
        } catch (Exception exception) {
            String s;
            Throwable cause = exception.getCause();
            if (cause instanceof SQLIntegrityConstraintViolationException) {
                String sqlState = ((SQLIntegrityConstraintViolationException) cause).getSQLState();
                s = "Dao.insert:表中已存在主键,已设置允许忽略次此异常";
                log.debug(s);
                if (!ignoreDuplicateExceptionYn) {
                    throw new Exception(s);
                }
            } else {
                s = "Dao.insert:保存失败";
                log.error(s, exception);
                throw new Exception(s);
            }

        }

        return String.join(",",collect);

    }







    @Override
    public void update(SysUserMpgtPojo pojo) throws Exception {
        if (pojo.getUserId() == null) {
            throw new Exception("ID不能为空");
        }
        sysUserMpgtMapper.updateById(pojo);
    }


    @Override
    public void delete( IdQo idQo) throws Exception {
        String id = idQo.getId();
        Long tableYear = idQo.getTableYear();
        if (StringUtils.isBlank(id)) {
            throw new Exception("ID不能为空");
        }
        SysUserMpgtPojo pojo = new SysUserMpgtPojo();
        pojo.setUserId(Long.parseLong(id));
        pojo.setTableYear(tableYear);
        sysUserMpgtMapper.deleteById(pojo);
    }

    private QueryWrapper getQueryWrapper(SysUserMpgtKbo sysUserMpgtKbo, SysUserMpgtQo sysUserMpgtQo) throws IllegalAccessException {
        SysUserMpgtPojo sysUserMpgtPojo = BeanUtil.toBean(sysUserMpgtQo, SysUserMpgtPojo.class);
        QueryWrapper<SysUserMpgtPojo> queryWrapper = new QueryWrapper(sysUserMpgtPojo);
        if(sysUserMpgtKbo!=null){
            //通过getDeclaredFields()方法获取对象类中的所有属性（含私有）
            Field[] fields = sysUserMpgtKbo.getClass().getDeclaredFields();
            List<Field> fieldNotNullNotBlankList = new ArrayList<>();
            for (Field field : fields) {
                //设置允许通过反射访问私有变量
                field.setAccessible(true);
                //获取字段属性名称
                String name = field.getName();
                //获取字段的值
                Object value = field.get(sysUserMpgtKbo);

                //其他自定义操作
                if (value != null || StringUtils.isNotBlank((String) value)) {
                    fieldNotNullNotBlankList.add(field);
                }
            }

            List<String> collect = fieldNotNullNotBlankList.stream().map(e -> com.audaque.springboot.foshanupload.core.util.StringUtils.toCamelCase(e.getName())).collect(Collectors.toList());
            String[] fieldNameNotNullNotBlankArr = collect.toArray(new String[collect.size()]);
            queryWrapper.select(fieldNameNotNullNotBlankArr);
        }

        return queryWrapper;
    }


    @Override
    public Page<SysUserMpgtPojo> queryAndCount(SysUserMpgtKbo sysUserMpgtKbo, SysUserMpgtQo sysUserMpgtQo) throws IllegalAccessException {
        Page<SysUserMpgtPojo> page = sysUserMpgtQo.toPage();
        com.baomidou.mybatisplus.extension.plugins.pagination.Page page1 = new com.baomidou.mybatisplus.extension.plugins.pagination.Page(page.getPage(), page.getRows());
        QueryWrapper queryWrapper = this.getQueryWrapper(sysUserMpgtKbo, sysUserMpgtQo);
        sysUserMpgtMapper.selectPage(page1, queryWrapper);
        page.setRecords(page1.getRecords());
        return page;
    }


    @Override
    public List<SysUserMpgtPojo> queryList(SysUserMpgtKbo sysUserMpgtKbo, SysUserMpgtQo sysUserMpgtQo) throws IllegalAccessException {
        QueryWrapper queryWrapper = this.getQueryWrapper(sysUserMpgtKbo, sysUserMpgtQo);
        List list = sysUserMpgtMapper.selectList(queryWrapper);
        return list;
    }

    @Override
    public SysUserMpgtPojo queryItem(SysUserMpgtKbo sysUserMpgtKbo, SysUserMpgtQo sysUserMpgtQo) throws IllegalAccessException {
        QueryWrapper queryWrapper = this.getQueryWrapper(sysUserMpgtKbo, sysUserMpgtQo);
        SysUserMpgtPojo sysUserMpgtPojo = sysUserMpgtMapper.selectOne(queryWrapper);
        return sysUserMpgtPojo;
    }

    @Override
    public SysUserMpgtPojo queryItem(String id) throws Exception {
        if (StringUtils.isBlank(id)) {
            throw new Exception("ID不能为空");
        }
        SysUserMpgtPojo sysUserMpgtPojo = sysUserMpgtMapper.selectById(id);
        return sysUserMpgtPojo;
    }

    @Override
    public Integer count(SysUserMpgtQo sysUserMpgtQo) {
        QueryWrapper queryWrapper = new QueryWrapper(sysUserMpgtQo);
        Long l = sysUserMpgtMapper.selectCount(queryWrapper);
        return l.intValue();
    }
}
